package com.lingo.a2b.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingo.a2b.common.exception.BizException;
import com.lingo.a2b.common.util.ReflectionUtils;
import com.lingo.a2b.mapper.ConnectProjectMapper;
import com.lingo.a2b.model.bo.ClassInfo;
import com.lingo.a2b.model.entity.ConnectFieldRelative;
import com.lingo.a2b.model.entity.ConnectProjectDO;
import com.lingo.a2b.model.vo.FieldInfoVo;
import com.lingo.a2b.service.ConnectFieldRelativeService;
import com.lingo.a2b.service.ConnectProjectService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lingo
 * @since 2020-05-21
 */
@Service
public class ConnectProjectServiceImpl extends ServiceImpl<ConnectProjectMapper, ConnectProjectDO> implements ConnectProjectService {

    private static Logger logger = LoggerFactory.getLogger(ConnectProjectServiceImpl.class);

    @Resource
    private ConnectFieldRelativeService connectFieldRelativeService;

    @SneakyThrows
    @Override
    public List<FieldInfoVo> listFieldVoById(Integer fprojectId) {
        QueryWrapper<ConnectProjectDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ConnectProjectDO::getFid, fprojectId);
        ConnectProjectDO one = this.getOne(queryWrapper);
        if (one == null) {
            return null;
        }
        List<ConnectFieldRelative> fieldRelativeList = connectFieldRelativeService.listByProjectId(fprojectId);
        String fvoClassName = one.getFvoClassName();
        ClassInfo info = ReflectionUtils.getClassInfo(Class.forName(fvoClassName), fieldRelativeList);
        return info.toFieldInfoVo(fprojectId);
    }

    @Override
    public int register(ConnectProjectDO entity) {
        boolean isPresent = ClassUtils.isPresent(entity.getFvoClassName(), this.getClass().getClassLoader());
        if (!isPresent) {
            throw new BizException("类不存在:" + entity.getFvoClassName());
        }
        super.save(entity);
        return entity.getFid();
    }
}
